package gov.nist.healthcare.testframework.communication.mllp.client;

import gov.nist.healthcare.core.MalformedMessageException;
import gov.nist.healthcare.core.Constants.MessageEncoding;
import gov.nist.healthcare.core.message.HL7Message;
import gov.nist.healthcare.core.message.v2.er7.Er7Message;
import gov.nist.healthcare.core.message.v2.xml.XmlMessage;
import gov.nist.healthcare.testframework.communication.MllpUtils;
import gov.nist.healthcare.testframework.communication.client.ClientThread;
import java.io.IOException;
import java.io.InputStream;
import org.apache.log4j.Logger;

public class MLLPClient extends ClientThread {

    private static final Logger logger = Logger.getLogger(MLLPClient.class.getName());
    private final MessageEncoding encoding;

    /**
     * Constructor
     * 
     * @param secure
     * @param encoding
     */
    public MLLPClient(boolean secure, MessageEncoding encoding) {
        this.secure = secure;
        this.encoding = encoding;
    }

    @Override
    public String encode(HL7Message message) {
        return encode(message, null);
    }

    @Override
    public String encode(HL7Message message, String endpoint) {
        return MllpUtils.wrapMessage(message);
    }

    @Override
    public HL7Message getMessage() {
        HL7Message message = null;
        try {
            InputStream in = socket.getInputStream();
            String msg = null;
            msg = MllpUtils.extractMessage(in);
            if (encoding == MessageEncoding.V2_ER7) {
                message = new Er7Message(msg);
            } else if (encoding == MessageEncoding.V2_XML) {
                message = new XmlMessage(msg);
            }
        } catch (IOException ioe) {
            logger.debug("Exception when reading the input stream", ioe);
        } catch (MalformedMessageException mme) {
            logger.debug("Exception when creating an Er7 message", mme);
        }
        return message;
    }

}
